new Vue({
	el: '#mainBody',
	data: function () {
		return {
			showDialog: false,
			viewTitle: '',
			searchForm: {
				templateName: '',
				templateType: ''
			},
			templateTypes: [],
			templateForm: {
				templateName: '',
				templateType: '',
				templateNotes: '',
				templateTips: '',
				templateImgList: [],
				templateFileList: []
			},
			isDisabled: false,
			isAdd: false, //新建下载模板
			currentpage:1,//当前页数
            pageBean:[//分页参数列表
            ],
            searchJson:[],
			templateList: [ { } ], //数据类型列表
			showRules: { //新增form 验证
				templateName: [
                    {required: true, message: '名称不能为空', trigger: 'blur'},
                    {min:2,max:20,message:'长度在 2 - 20 个字符',trigger:'blur'}
                ],
                templateType: [
                    {required: true, message: '模板类型不能为空', trigger: 'change'}
                ],
                templateImgList:[
                    {required: true, message: '图片说明不能为空', trigger: 'change'}
                ],
                templateFileList:[
                    {required: true, message: '竞赛模板不能为空', trigger: 'change'}
                ],
            }
		}
	},
	created: function () {
        //页面加载查询人力列表
        this.findAllRaceTemplate();
        //页面加载查询数据字典数据
        this.getGlobalConstraints();
    },
	methods: {
		uploadFile: function(type){
    		return "/uploadRaceFile/" + type;
    	},
    	handlePreview: function () {
            // 点击已上传的文件链接时的钩子，可以通过file.response拿到服务端返回数据
        },
        handleRemove: function (file, fileList) {
            // 文件列表移除文件时的钩子
        	console.log(file)
        	console.log(file.type)

        	if(file.type == 'img'){
        		this.templateForm.templateImgList = ''
        	}
        	if(file.type == 'file'){
        		this.templateForm.templateFileList = ''
        	}
			
        	//var index = file.index;
        	//this.ruleForm.files[index].fileList=fileList;
        },
        beforeRemove: function (file, fileList) {
            // 删除文件之前的钩子，参数为上传的文件和文件列表，若返回false或者返回Promise且被reject，则停止上传。
        	return this.$confirm('确定移除' + file.name)
        },
    	uploadSuccess: function(response, file, fileList) {
        	var att = response.data;
        	if(att.type == "img"){
        		this.templateForm.templateImgList = att.templateList;
        	}
        	if(att.type == "file"){
        		this.templateForm.templateFileList = att.templateList;
        	}
        	file.type = att.type;
          console.log('上传文件', response)
        },
        // 上传错误
        uploadError: function(response, file, fileList) {
          console.log('上传失败，请重试！')
        },
        handleExceed: function (file, fileList) {
              // 文件超出个数限制时的钩子
              this.$message.warning('当前限制选择1个文件')
        },
		/**
    	 * 下一页上一页按钮
    	 * */
    	handleCurrentChange:function(val){
    		this.currentpage=val;
    		var _this = this;
			this.searchRaceTemplate();
    	},
    	/**
         * 改变查询条件
         */
        changeSearch: function () {
        	var _this = this;
        	_this.searchJson = JSON.stringify(this.searchForm);
        	_this.currentpage = 1;
        	_this.searchRaceTemplate();
        },
        /**
         * 查询全部的竞赛模板
         */
    	findAllRaceTemplate:function() {
            var _this = this
            $.ajax({
                url: '/findAllRaceTemplate',
                type: 'post',
                data:{"page":_this.currentpage},
                dataType: 'json',
                success: function (res) {
                    _this.templateList = res.data.beanList
                    var page = {}
                    page['totalNumber'] = res.data.totalNumber
                    page['pageSize'] = res.data.size
                    _this.pageBean = page
                },
                error: function (err) {
                    if(err.responseJSON.message=="session clean"){
                        errorMessage(_this.$message, '登陆已失效重新登陆!');
                        toLogin();
                        return;
                    }else if(err.status == 403){
                        errorMessage(_this.$message, "没有权限，请先申请该权限！");
                        return;
                    }
                    errorMessage(_this.$message, '查询竞赛模板列表出错！错误代码：'+(err.status))
                }
            })
        },
        /**
         * 获取数据字典数据
         */
        getGlobalConstraints:function(){
            var _this = this;
            $.ajax({
                url: '/getGlobalConstraints',
                type: 'get',
                dataType: 'json',
                success: function (res) {
                    _this.templateTypes = res.data.templateType
                },
                error: function (err) {
                	if(err.responseJSON.message=="session clean"){
                        errorMessage(_this.$message, '登陆已失效重新登陆!');
                        toLogin();
                        return;
                    }else if(err.status == 403){
                        errorMessage(_this.$message, "没有权限，请先申请该权限！");
                        return;
                    }
                    errorMessage(_this.$message, '查询人数据字典出错！错误代码：'+(err.status))
                }
            })
        },
		addTemplate: function () {
			var _this = this
            console.info("点击了新建竞赛模板按钮！！！！！")
        	_this.templateForm={}
			_this.templateForm.templateImgList = []
			_this.templateForm.templateFileList = []
			_this.isDisabled = false
			_this.showDialog = true
			_this.isAdd = true
			_this.viewTitle = '新建下载模板'
		},
		resetSearchForm: function (formName) {
			this.$refs[formName].resetFields()
		},
		closeDialog: function (formName) {
			this.templateForm.templateImgList = []
			this.templateForm.templateFileList = []
			this.$refs[formName].clearValidate()
		},
		saveForm: function (formName) { // 新建保存
            console.info("点击了新建弹窗的保存按钮")
            var _this = this
            this.$refs[formName].validate(function (valid) {
                if (valid) {
                	var fileList = _this.templateForm.templateFileList;
                	if (fileList== undefined || fileList=='' || fileList.length==0) {
                		errorMessage(_this.$message, "请选择上传附件");
					} else {
						$.ajax({
	                        url: '/addRaceTemplate',
	                        type: 'post',
	                        data: {"data":JSON.stringify(_this.templateForm)},
	                        dataType: 'json',
	                        success: function (res) {
	                            if(res != null){
	                                successMessage(_this.$message, '创建成功！');
	                                _this.showDialog = false
	                                _this.searchRaceTemplate();
	                            }else if(err.status == 403){
	                                errorMessage(_this.$message, "没有权限，请先申请该权限！");
	                                return;
	                            }else{
	                                warningMessage(_this.$message, '创建失败！');
	                            }

	                        },
	                        error: function (err) {
	                        	if(err.responseJSON.message=="session clean"){
	                                errorMessage(_this.$message, '登陆已失效重新登陆!');
	                                toLogin();
	                                return;
	                            }else if(err.status == 403){
	                                errorMessage(_this.$message, "没有权限，请先申请该权限！");
	                                return;
	                            }
	                            errorMessage(_this.$message,err.responseJSON.message );
	                            return false
	                        }
	                    })
	                    _this.showDialog = false
					}
                }
            })
        },
        /**
         * 查询竞赛模板
         */
        searchRaceTemplate: function () {
        	var _this = this;
        	if (_this.searchJson.length==0) {
        		_this.findAllRaceTemplate()
        		return
			}
        	$.ajax({
	            url: '/searchRaceTemplate',
	            type: 'post',
	            data: {"data":_this.searchJson,"page":_this.currentpage},
	            dataType: 'json',
	            success: function (res) {
	            	_this.templateList = res.data.beanList
	            	var page = {}
                    page['totalNumber'] = res.data.totalNumber
                    page['pageSize'] = res.data.size
                    _this.pageBean = page
	            },
                error: function (err) {
                    if(err.responseJSON.message=="session clean"){
                        errorMessage(_this.$message, '登陆已失效重新登陆!');
                        toLogin();
                        return;
                    }else if(err.status == 403){
                        errorMessage(_this.$message, "没有权限，请先申请该权限！");
                        return;
                    }
                    errorMessage(_this.$message, '查询竞赛模板失败!');
                }
	        })
        },
		updateForm: function (formName) { //修改保存
			console.info("点击了修改模板弹窗的保存按钮！！！！")
            var _this = this;
			this.$refs[formName].validate(function (valid) {
                if (valid) {
                	var fileList = _this.templateForm.templateFileList;
                	console.info(fileList)
                	if(fileList== undefined || fileList=='' || fileList.length==0){
                		errorMessage(_this.$message, "请选择上传附件");
                	}else{
                		$.ajax({
                            url: '/updateRaceTemplateById',
                            type: 'post',
                            data: {"data":JSON.stringify(_this.templateForm)},
                            dataType: 'json',
                            success: function (res) {
                            	successMessage(_this.$message, '修改成功');
                                _this.searchRaceTemplate();

                            },
                            error: function (err) {
                            	if(err.responseJSON.message=="session clean"){
                                    errorMessage(_this.$message, '登陆已失效重新登陆!');
                                    toLogin();
                                    return;
                                }else if(err.status == 403){
                                    errorMessage(_this.$message, "没有权限，请先申请该权限！");
                                    return;
                                }
                            	_this.searchRaceTemplate();
                                errorMessage(_this.$message,err.responseJSON.message );
                                return false
                            }
                        })
                        _this.showDialog = false
                	}
                }
            })
		},
		downloadFile: function (index) {
			 if(this.templateList[index].templateFileList == null){
				 alert("没有模板，下载失败！")
				 return false
			 }
	       	 var name = this.templateList[index].templateFileList[0].name
	       	 var filepath = this.templateList[index].templateFileList[0].url
	       	 var _this = this;
	       	 var templateJson = JSON.stringify(_this.templateList[index].templateFileList[0]);
	       	 window.location.href='/downloadRaceTemplate?data='+encodeURIComponent(templateJson);
	    },
	    downloadImg: function (index) {
			 if(this.templateList[index].templateFileList == null){
				 alert("没有图片说明，下载失败！")
				 return false
			 }
	       	 var name = this.templateList[index].templateImgList[0].name
	       	 var filepath = this.templateList[index].templateImgList[0].url
	       	 var _this = this;
	       	 var templateJson = JSON.stringify(_this.templateList[index].templateImgList[0]);
	       	 window.location.href='/downloadRaceTemplate?data='+encodeURIComponent(templateJson);
	    },
	    downloadRAR: function () {
	    	var downloadUrl = "http://128.232.236.38/race.rar"
	    	window.location.href = downloadUrl
	    },
		viewItem: function(index) { //查看
			var _this = this
			this.showDialog = true
			this.selectedForm = index
			this.templateForm = JSON.parse(JSON.stringify(this.templateList[index]))
			this.viewTitle = '查看模板详情'
			this.isDisabled = true
			this.isAdd = false
			setTimeout(function(){
				var eleA = document.createElement('a')
				eleA.setAttribute('target', '_blank')
				if (_this.templateForm.templateImgList!=undefined  &&  _this.templateForm.templateImgList!=null) { 
					eleA.setAttribute('href', _this.templateForm.templateImgList[0].url)
					var eleWrap = document.querySelector('.el-upload-list__item-thumbnail').parentNode
					eleWrap.appendChild(eleA)
					var childI = document.querySelector('.el-upload-list__item-thumbnail')
					eleA.appendChild(childI)
				}
				
			},500)
		},
		changeItem: function(index) { //修改
			this.showDialog = true
			this.selectedForm = index
			this.templateForm = JSON.parse(JSON.stringify(this.templateList[index]))
			
			if (this.templateForm.templateImgList!=undefined  &&  this.templateForm.templateImgList!=null) { 
				var url = this.templateForm.templateImgList[0].url;
		       	console.info(url)
				this.templateForm.templateImgList[0].url = url;
			}
			
			this.viewTitle = '修改模板详情'
			this.isDisabled = false
			this.isAdd = false
		},
		deleteItem: function(index) { //删除
			this.selectedForm = index
			this.templateList.splice(this.selectedForm,1)
		}
	}
})
